#This is a sample script to extract strict consensus files from nexus treefiles written by TNT and calculate tree distance & similarity metrics relative to a reference tree 
#Script received by Robert J. Asher, Dept Zoology, University of Cambridge on the 25th of March 2020 and then adapted for use in this thesis
#Please do not distribute without permission from Robert J. Asher

# needs these libraries to run
library(distory)
library(phangorn)
library(data.table) #enable library with fread command
library(TreeTools)
library(Quartet)


# script to extract strict consensus files
# output of this loop is file "treesstrict.txt" which has strict consensus of TNT treefiles corresponding to each subject & template (as extracted from filenames)
prefix<-"rtx" #change pattern to suit names of tnt output files
treesStrict<-"treesStrict.txt" #define variable for later writing
suffix<-".out" #change pattern to suit names of tnt output files
# script to extract TNT trees from text files in working directory
z<-list.files(path=".",pattern=suffix,recursive=F) 
for (i in 1:length(z) ){ #define for-loop to go through each filename in z
  filename<-gsub(suffix,"",z[i])
  filename<-gsub(prefix,"",filename)
  template<-gsub(".*?\\_","",filename)
  subject<-gsub("\\_.*","",filename)
  lineStrict<-length(count.fields(file=z[i],blank.lines.skip = F))-3 #TNT writes strict consensus 4 lines from the end, read by count.fields as 5, so length(count.fields[file])-3 has last newick topology written to TNT outfile
  strict <- read.table(z[i],skip = lineStrict, nrows=1, sep=";", header=F) #reads into variable tree one row of text from file z[i] starting at lineStrict 
  write(paste(subject,"=",template,"=",strict$V1,";",sep=" "),file=treesStrict,append=T)
} #close for-loop

#read "treesstrict.txt" and convert into data frame "rtxTrees"
rtxTrees<-read.table("treesstrict.txt",sep="=",col.names = c("subject","template","topo")) #write each line as an observation with columns separated by "=" 
#read column with topologies and write each line to a new file
write(paste(rtxTrees$topo), file="rtxTrees.nwk") 


# calculate tree distances and clades in common using prop.clades
# the following loop writes the file "RF_shared.csv", a spreadsheet with proportion resolved, RF, cRF or RF scaled by resolution, and number of shared splits between each testtree and reftree 
reftree<-read.tree("wellcorr.nwk") # pick your reference tree (e.g., "wellcorr.nwk")
testtrees<-read.tree("rtxTrees.nwk") # read topology from testtrees.txt column V2, saved previously as "rtxTrees.nwk"
#the previous line reads testtrees from "rtxTrees.nwk"
outfile <- "RF_shared.csv" # define file for writing in loop below
write(paste("subject","template","resolved","RF","cRF","shared","QD",sep = ","),  file = outfile, append = T) #write column labels for loop below
for (i in 1:length(testtrees) ){
  refTaxa <- reftree$tip.label
  tree <- testtrees[[i]]
  thisTaxa <- tree$tip.label
  tree <- drop.tip(tree, setdiff(thisTaxa, refTaxa))
  reftreeTemp <- drop.tip(reftree, setdiff(refTaxa, thisTaxa)) # this prunes tips in reftree to those in common between reftree and testtree[i]
  pbif<-NSplits(NTip(tree)) # possible bifurcating, fully resolved unrooted tree has ntax - 1 nodes as written by TNT
  bif<-NSplits(tree) #"bif" = actual bifurcating, number of actually resolved nodes in tree[i]
  res<-bif/pbif #resolved/total possible resolved = proportion out of 1 resolved
  RF <- TreeDist::RobinsonFoulds(tree, reftreeTemp)
  cRF<-RF/res
  shared<-sum(as.Splits(tree) %in% as.Splits(reftreeTemp))
  statuses <- QuartetStatus(tree, reftreeTemp) #suggested by Martin Smith
  QD<-QuartetDivergence(statuses,similarity = T)
  # next line writes output
  write(paste(rtxTrees$subject[i],rtxTrees$template[i],res,RF,cRF,shared,QD,sep = ","),  file = outfile, append = T)
}

#Here you can read back the csv file into dataframe "RFS", then get averages etc. for subjects per template, etc.
RFS<-read.csv(file.choose("RF_shared.csv"),header = T) #this should be "RF_shared.csv" file with stats for every subject-template combination
dt<-data.table(RFS)
shared<-dt[, list(shared.mean=sapply(.SD,mean), shared.median=sapply(.SD, median), shared.stdev=sapply(.SD, sd)), #"list()" gives column names before sapply, "(.SD,fun)" is corresponding function, each given its own column in output
           by="template", .SDcols=c("shared")] # "by" is row category for row treatments; ".SDcols" gives values for each treatment (each given a row)
cRF<-dt[, list(cRF.mean=sapply(.SD,mean), cRF.median=sapply(.SD, median), cRF.stdev=sapply(.SD, sd)), #"list()" gives column names before sapply, "(.SD,fun)" is corresponding function, each given its own column in output
        by="template", .SDcols=c("cRF")] # "by" is row category for row treatments; ".SDcols" gives values for each treatment (each given a row)
QD<-dt[, list(QD.mean=sapply(.SD,mean), QD.median=sapply(.SD, median), QD.stdev=sapply(.SD, sd)), #"list()" gives column names before sapply, "(.SD,fun)" is corresponding function, each given its own column in output
           by="template", .SDcols=c("QD")] # "by" is row category for row treatments; ".SDcols" gives values for each treatment (each given a row)

#load & add metadata
meta<-read.csv("rtxMeta.csv",header = T)
#make sure that templates correspond exactly in row order before combining columns 
shared<-shared[order(shared$template),]
cRF<-cRF[order(cRF$template),]
QD<-QD[order(QD$template),]
#combine columns
rtx<-cbind(meta,shared,cRF,QD)
#check that template columns in rtx correspond and then delete extraneous column
rtx[,12]<-NULL #REMEMBER to check if the column you want to delete is "12"
rtx[,8]<-NULL #REMEMBER to check if the column you want to delete is "8"
rtx[,14]<-NULL
write.csv(rtx,file = "rtxAimeGlires.csv",row.names = F)

